package com.efast.cafe.portal.service.company.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;


import com.efast.cafe.portal.bean.company.PortalCompanyUserRoleBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import com.efast.cafe.framework.constant.CommonConstant;
import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.jdbc.JdbcDao;
import com.efast.cafe.framework.jdbc.JdbcDaoImpl;
import com.efast.cafe.framework.jdbc.persistence.Criteria;
import com.efast.cafe.framework.redis.ObjectRedisTemplate;
import com.efast.cafe.framework.service.CafeServiceImpl;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.cafe.portal.bean.company.PortalCompanyRoleQueryBean;
import com.efast.cafe.portal.dao.company.PortalCompanyRoleDao;
import com.efast.cafe.portal.entity.company.PortalCompanyRole;
import com.efast.cafe.portal.entity.company.PortalCompanyRolePurview;
import com.efast.cafe.portal.entity.company.PortalCompanyUserRole;
import com.efast.cafe.portal.service.company.IPortalCompanyRoleService;
import com.google.common.collect.Sets;

@Service
@Transactional
@RestController
public class PortalCompanyRoleServiceImpl extends CafeServiceImpl<PortalCompanyRole> implements IPortalCompanyRoleService {

	@Qualifier("jdbcDao")
	@Autowired
	private JdbcDao jdbcDao;

	private ObjectRedisTemplate objectRedisTemplate;

	@Autowired
	private PortalCompanyRoleDao portalCompanyRoleDao;
	

	@Autowired
	public void setObjectRedisTemplate(ObjectRedisTemplate objectRedisTemplate) {
		this.objectRedisTemplate = objectRedisTemplate;
	}
	
	

	@Override
	public PortalCompanyRoleQueryBean queryPageRoleList(String roleName, PortalCompanyRoleQueryBean bean) {
		String companyCode = SpringWebUtils.getRequestCompany();
	/*	Criteria criteria = Criteria.create(PortalCompanyRole.class).where("companyCode",new Object[] { companyCode });
		if (StringUtils.isNotBlank(roleName)) {
			criteria.and("roleName", Criteria.FIELD_OPERATOR_LIKE, new Object[] { "%" + roleName + "%" });
		}
		if (StringUtils.isNotBlank(pager.getOrderBy()) && StringUtils.isNotBlank(pager.getSort())) {
			if (pager.getSort().equals("asc"))
				criteria.asc(pager.getOrderBy());
			else
				criteria.desc(pager.getOrderBy());
		} else {
			criteria.desc("createTime");
		}
		return jdbcDao.queryListByPage(pager, criteria);*/
		bean.setRoleName(roleName);
		bean.setCompanyCode(companyCode);
		bean.setResultList(portalCompanyRoleDao.queryRoleList(bean));
		bean.setTotalRows(portalCompanyRoleDao.queryRoleCount(bean));
		return bean;
	}

	@Override
	public Long insertRole(PortalCompanyRole role,Long[] purviewIds) {
		String companyCode = SpringWebUtils.getRequestCompany();
		int checkCount = jdbcDao.queryCount(Criteria.create(PortalCompanyRole.class).where("companyCode",Criteria.FIELD_OPERATOR_IN, new Object[] { companyCode,"system"})
						.and("roleName", new Object[] { role.getRoleName() }));
		if(checkCount!=0){
			throw new ServiceException("角色名重复");
		}
		role.setCompanyCode(companyCode);
		role.setParentId(1L);
		//role.setIsDefaultRole(0);
		Long id = jdbcDao.insert(role);
		saveRolePurview(id,purviewIds);
		return id;
	}

	@Override
	public void updateRole(PortalCompanyRole role,Long[] purviewIds) {
		String companyCode = SpringWebUtils.getRequestCompany();
		if (null == role.getPortalCompanyRoleId()) {
			throw new ServiceException("role id is null.");
		} else {
			int checkCount = jdbcDao.queryCount(Criteria.create(PortalCompanyRole.class)
					.where("companyCode",Criteria.FIELD_OPERATOR_IN, new Object[] { companyCode,"system"})
					.and("portalCompanyRoleId", Criteria.FIELD_OPERATOR_NOT, new Object[]{role.getPortalCompanyRoleId()})
					.and("roleName", new Object[] { role.getRoleName() }));
			if(checkCount>0){
				throw new ServiceException("角色名重复");
			}
			jdbcDao.update(Criteria.create(PortalCompanyRole.class).set("roleName", role.getRoleName())
					.set("isDefaultRole", role.getIsDefaultRole())
					.set("roleRemark", role.getRoleRemark())
					.where("portalCompanyRoleId", new Object[] { role.getPortalCompanyRoleId() })
					.and("companyCode", new Object[] { companyCode }));
			saveRolePurview(role.getPortalCompanyRoleId(),purviewIds);
		}
	}

	@Override
	public void deleteRole(Long roleId) {
		String companyCode = SpringWebUtils.getRequestCompany();
		// 先删除角色和权限对应的关系
		jdbcDao.delete(
				Criteria.create(PortalCompanyRolePurview.class).where("portalCompanyRoleId", new Object[] { roleId })
						.and("companyCode", new Object[] { companyCode }));
		// 删除用户和角色的关系
		Criteria userRoleCriteria = Criteria.create(PortalCompanyUserRole.class)
				.where("portalCompanyRoleId", new Object[] { roleId }).and("companyCode", new Object[] { companyCode });
		jdbcDao.delete(userRoleCriteria);
		// 删除角色
		jdbcDao.delete(Criteria.create(PortalCompanyRole.class).where("portalCompanyRoleId", new Object[] { roleId })
				.and("companyCode", new Object[] { companyCode }));
		// 删除角色后 清除redis相关缓存
		// 查出所影响的用户
		List<PortalCompanyUserRole> userRoleList = jdbcDao.queryList(userRoleCriteria);
		List<String> redisKeys = new ArrayList<String>();
		for (PortalCompanyUserRole userRole : userRoleList) {
			String key1 = CommonConstant.REDIS_COMPANYUSER_PURVIEW_IDS_KEY + companyCode + userRole.getUsername();
			String key2 = CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY + companyCode + userRole.getUsername();
			if (!redisKeys.contains(key1)) {
				redisKeys.add(key1);
			}
			if (!redisKeys.contains(key2)) {
				redisKeys.add(key2);
			}
		}
		if (redisKeys.size() > 0) {
			// 清除redis缓存
			// 清除当前用户所拥有的权限ID
			// 清除用户拥有的权限URL
			objectRedisTemplate.delete(redisKeys);
		}
	}

	@Override
	public PortalCompanyRole getCompanyRoleById(Long portalCompanyRoleId) {
		String companyCode = SpringWebUtils.getRequestCompany();
		return jdbcDao.querySingleResult(
				Criteria.create(PortalCompanyRole.class).where("companyCode", new Object[] { companyCode })
						.and("portalCompanyRoleId", new Object[] { portalCompanyRoleId }));
	}

	@Override
	public void saveRolePurview(Long portalCompanyRoleId, Long[] purviewIds) {
		String companyCode = SpringWebUtils.getRequestCompany();
		String username = SpringWebUtils.getRequestUser();
		jdbcDao.delete(Criteria.create(PortalCompanyRolePurview.class)
				.where("portalCompanyRoleId", new Object[] { portalCompanyRoleId })
				.and("companyCode", new Object[] { companyCode }));
		if (null != purviewIds) {
			for (Long modulePurviewId : purviewIds) {
				jdbcDao.insert(Criteria.create(PortalCompanyRolePurview.class).set("companyCode", companyCode)
						.set("portalCompanyRoleId", portalCompanyRoleId).set("modulePurviewId", modulePurviewId)
						.set("createUser", username).set("createTime", new Date()).set("lastUpdateUser", username)
						.set("lastUpdateTime", new Date()));
			}
		}
		// 找出角色所影响的用户
		Criteria userRoleCriteria = Criteria.create(PortalCompanyUserRole.class)
				.where("portalCompanyRoleId", new Object[] { portalCompanyRoleId })
				.and("companyCode", new Object[] { companyCode });
		// 删除redis对应的缓存
		List<PortalCompanyUserRole> userRoleList = jdbcDao.queryList(userRoleCriteria);
		List<String> redisKeys = new ArrayList<String>();
		for (PortalCompanyUserRole userRole : userRoleList) {
			String key1 = CommonConstant.REDIS_COMPANYUSER_PURVIEW_IDS_KEY + companyCode + userRole.getUsername();
			String key2 = CommonConstant.REDIS_COMPANYUSER_PURVIEWSET_KEY + companyCode + userRole.getUsername();
			if (!redisKeys.contains(key1)) {
				redisKeys.add(key1);
			}
			if (!redisKeys.contains(key2)) {
				redisKeys.add(key2);
			}
		}
		// 清除redis缓存
		// 清除当前用户所拥有的权限ID
		// 清除用户拥有的权限URL
		if (redisKeys.size() > 0) {
			objectRedisTemplate.delete(redisKeys);
		}
	}

	@Override
	public HashSet<Long> queryPurviewByRole(Long portalCompanyRoleId) {
		String companyCode = SpringWebUtils.getRequestCompany();
		List<PortalCompanyRolePurview> list = jdbcDao.queryList(
				Criteria.create(PortalCompanyRolePurview.class).where("company_code", new Object[] { companyCode })
						.and("portal_company_role_id", new Object[] { portalCompanyRoleId }));
		HashSet<Long> authSet = Sets.newHashSet();
		for (PortalCompanyRolePurview p : list) {
			authSet.add(p.getModulePurviewId());
		}
		return authSet;
	}

	@Override
	public List<PortalCompanyRole>  queryRoleAll(String roleName) {
		
		return portalCompanyRoleDao.queryRoleAll(roleName,SpringWebUtils.getRequestCompany());
		
	}




	/* (非 Javadoc)
	    * 
	    * 
	    * @param companyCode
	    * @param username
	    * @return
	    * @see com.efast.cafe.portal.remote.company.PortalCompanyRoleService#queryRoleByUser(java.lang.String, java.lang.String)
	    */
	    
	@Override
	public List<PortalCompanyRole> queryRoleByUser(String companyCode, String username) {
		// TODO Auto-generated method stub
		return portalCompanyRoleDao.queryRoleByUser(username, companyCode);
	}

}
